<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="searchList" :model="searchList">

        <el-input v-model="searchList.empName" placeholder="请输入姓名" style="width: 200px;" class="filter-item"
          @keyup.enter.native="handleFilter" />

        <el-select v-model="searchList.deptId" clearable style="width: 90px" class="filter-item" placeholder="部门">
          <el-option v-for="item in empDeptOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
        </el-select>

        <el-select v-model="searchList.empDegreeName" placeholder="学历" clearable class="filter-item" style="width: 130px">
          <el-option label="研究生" value="研究生"></el-option>
          <el-option label="本科" value="本科"></el-option>
          <el-option label="大专" value="大专"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>

      </el-form>
    </div>

    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
        @click="handleDownload" :default-active="$route.path">
        导出
      </el-button>
    </div>

    <!-- 页面表格数据 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="emplist" border fit highlight-current-row
      style="width: 100%;">
      <el-table-column label="序号" prop="empId" width="90"></el-table-column>
      <el-table-column label="职工姓名" prop="empName" width="130"> </el-table-column>
      <el-table-column label="性别" prop="sex" min-width="90"></el-table-column>
      <el-table-column label="年龄" prop="age" width="90"></el-table-column>
      <el-table-column label="部门名称" prop="deptName" width="130"> </el-table-column>
      <el-table-column label="学历" prop="empDegreeName" width="130"> </el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.empId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 自定义分页
        handleSizeChange改变展示数量的方法
        handleCurrentChange  改变分页的方法
        :current-page 当前页数
        page-sizes 初始分页数量
        total="total 总数量
     -->
    <el-pagination v-show="total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="currentPage" :page-sizes="[5, 10, 20, 40]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 自带分页
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" /> -->

    <!-- 编辑、添加弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="updateEmp" label-position="left" label-width="70px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="序号" prop="empId">
          <el-input v-model="updateEmp.empId" disabled="disabled" />
        </el-form-item>

        <el-form-item label="姓名" prop="empName">
          <el-input v-model="updateEmp.empName" />
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="updateEmp.sex" class="filter-item" placeholder="请选择性别">
            <el-option v-for="item in empSexOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="updateEmp.age" />
        </el-form-item>

        <el-form-item label="部门名称">
          <el-select v-model="updateEmp.deptId" class="filter-item" placeholder="请选择部门">
            <el-option v-for="item in empDeptOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>

        <el-form-item label="学历">
          <el-select v-model="updateEmp.empDegreeName" class="filter-item" placeholder="请选择学历">
            <el-option v-for="item in empDegreeNameOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, addEmp, updateEmployee, getDept, delEmpAndDept, getEmpAndDept, downloadEmp } from '@/api/employee'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { Pagination } from 'element-ui';


export default {
  name: 'EmployeeTable',
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      searchList: {
        empName: '',
        deptId: '',
        empDegreeName: ''
      },
      empsearchList: [],
      emplist: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      currentPage: 1,
      pageSize: 5,
      listQuery: {
        pageNum: 1,
        pageSize: 5,
      },
      empSexOptions: ['男', '女'],
      empDeptOptions: [],
      empDegreeNameOptions: ['大专', '本科', '研究生', '其他'],

      showReviewer: false,
      updateEmp: {
        empId: undefined,
        empName: '',
        sex: '',
        age: undefined,
        deptId: undefined,
        empDegreeName: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        empName: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  //页面加载时去掉对应的方法
  created() {
    this.getList()
    this.getDeptList()
  },
  methods: {
    handleSizeChange(val) {
      this.listQuery.pageSize = val //每页显示数量，点击每页展示条数时时请求
      //点击当前页码时请求的方法，在这里如果调用getList()，那么当用户使用条件检索时查出的数据点击下一页就无法正常展示
      this.handleFilter()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val //当前页码，点击当前页码时请求的参数
      /* 
      handleFilter() 方法是作为条件查询时调用的，其中的条件参数非必传
      getList() 是分页查询全部信息
      */
      this.handleFilter()
    },//分页查询
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        if (response.code === 20000) {
          this.emplist = response.data.list
          console.log(1234, response.data.list);
          this.total = response.data.total
          this.listQuery.pageNum = response.data.pageNum; // 当前页码
          this.listQuery.pageSize = response.data.pageSize; // 每页显示数量
        }
        // Just to simulate the time of the request 
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)

      })

    },//条件检索
    handleFilter() {
      getEmpAndDept(this.listQuery, this.searchList).then(response => {
        if (response.code === 20000) {
          this.emplist = response.data.list
          this.total = response.data.total
          this.listQuery.pageNum = response.data.pageNum; // 当前页码
          this.listQuery.pageSize = response.data.pageSize; // 每页显示数量
        }
      })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.updateEmp = {
        empId: 0,
        empName: '',
        sex: '',
        age: 0,
        deptId: 0,
        deptName: '',
        empDegreeName: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },//员工添加
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addEmp(this.updateEmp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },//获取部门信息
    getDeptList() {
      getDept(this.empDeptOptions).then(response => {
        this.empDeptOptions = response.data
      })
    },//职工更新弹窗，更新时需要获取部门信息
    handleUpdate(row) {
      this.updateEmp = row
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getDeptList()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

    },
    async updateData() {//职工更新方法
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateEmployee(this.updateEmp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })

        }
      })
      this.handleFilter()
      await this.getDeptList()
    },
    //删除职工信息
    async handleDelete(empId) {
      await delEmpAndDept(empId)
      this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      //删除成功后重新调用查询
      await this.getList()
    },
    //导出方法，无需调用后端导出接口
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        // 点击导出后先调用downloadEmp()从后端查出全部数据，赋值给const emplist1解析后导出为excel
        downloadEmp().then(response => {
          if (response.code === 20000) {
            const tHeader = ['序号', '职工姓名', '性别', '年龄', '部门名称', '学历']
            const filterVal = ['empId', 'empName', 'sex', 'age', 'deptName', 'empDegreeName']
            const emplist1 = response.data

            const data = this.formatJson(filterVal, emplist1)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '职工列表'
            })

          }
          this.downloadLoading = false
        })

       
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
  },
}
</script>
